package landlords;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * 玩家
 */
public class Player {

    // 玩家姓名
    private String name;

    // 玩家类型：农民/地主
    private String type;

    // 抓到的牌
    private List<Card> cards;

    public Player(String name, String type) {
        this.name = name;
        this.type = type;
        this.cards = new ArrayList<>();
    }

    // 洗牌 shuffle
    public void shuffle() {
        Collections.shuffle(this.cards);
    }

    // 理牌 sort
    public void sort() {
        Collections.sort(this.cards, Card::compareTo);
    }

    // 抓牌
    public void draw(Card card) {
        this.cards.add(card);
    }

    // 出牌
    public void play(Card card) {
        this.cards.remove(card);
    }

    // 找出最大牌 max
    public Card max() {
        return Collections.max(this.cards, Card::compareTo);
    }

    // 找出最小牌 min
    public Card min() {
        return Collections.min(this.cards, Card::compareTo);
    }

    // 找到指定牌的位置 binarySearch
    public int binarySearch(Card card) {
        return Collections.binarySearch(this.cards, card, Card::compareTo);
    }

    // 统计有几手炸弹 frequency
    public int frequency() {
        int count = 0;
        List<String> numbers= new ArrayList<>();
        List<String> colors= new ArrayList<>();
        for (int i = 0; i < this.cards.size(); i++) {
            colors.add(this.cards.get(i).getColor());
            numbers.add(this.cards.get(i).getNumber());
        }
        for (int j = 0; j < Constant.NUMBERS.size(); j++) {
            if (Collections.frequency(numbers, Constant.NUMBERS.get(j)) == 4) {
                count++;
            }
        }
        if (Collections.frequency(colors, "JOKER") == 2) {
            count++;
        }
        return count;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<Card> getCards() {
        return cards;
    }

    public void setCards(List<Card> cards) {
        this.cards = cards;
    }

    @Override
    public String toString() {
        StringBuilder poker = new StringBuilder("[");
        Iterator<Card> iterator = this.cards.iterator();
        while (iterator.hasNext()) {
            poker.append(iterator.next().toString() + ",");
        }
        poker.setCharAt(poker.length() - 1, ']');
        return this.getType() + ":" + this.getName() + "拿到" + this.cards.size() + "张牌：" + poker;
    }
}
